// import tracker from "../uilts/tracker";

export  function injectXHR() {
  
    let XMLHttpRequest = window.XMLHttpRequest;
  
    let oldOpen =  XMLHttpRequest.prototype.open;
     //重新写  MLHttpRequest.open
     XMLHttpRequest.prototype.open = function(method,url,async){
        //不是 阿里云的接口才监听
        if(!url.match(/logstores/)){
            this.logData = {method,url,async}
        }
        
         return  oldOpen.apply(this,arguments)
    }

    let oldSend =  XMLHttpRequest.prototype.send;
    //重新写  MLHttpRequest.send
   
    XMLHttpRequest.prototype.send = function(body){
       //this.logData有值已经被拦截
       if(this.logData){
        let starTime = Date.now();//在发送之前记录一下时间
        let handler = (type)=>(event)=>{
            let duration  = Date.now() - starTime;
            let status = this.status//200 500
            let statusText = this.statusText//ok  server Error
            let log ={
                kind:'stability',
                type:'xhr',
                eventType:type,//load  error  
                pathname:this.logData.url, //请求路径
                status:status+'-'+statusText,//状态码
                duration,//持续时间
                response:this.response?JSON.stringify(this.response):'',//响应提
                params:body||"",
            }
            console.log(log,'MLHttpRequest')

        }
        this.addEventListener('load',handler('load'),false)
        this.addEventListener('error',handler('error'),false)//请求失败
        this.addEventListener('abort',handler('abort'),false)//请求放弃
       }
        return  oldSend.apply(this,arguments)
   }

}
